package org.example.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import org.example.constant.MessageConstant;
import org.example.domain.GoodsMaterial;
import org.example.domain.Production;
import org.example.mapper.GoodsMaterialMapper;
import org.example.mapper.ProductionMapper;
import org.example.result.Result;
import org.example.service.ProductionService;
import org.example.dto.ProductionDto;
import org.example.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
* @author 19816
* @description 针对表【sys_production】的数据库操作Service实现
* @createDate 2024-05-30 17:06:44
*/
@Service
public class ProductionServiceImpl implements ProductionService{

    @Autowired
    private GoodsMaterialMapper goodsMaterialMapper;

    @Autowired
    private ProductionMapper productionMapper;

    @Autowired
    private HttpServletRequest request;

    public Result addGoods(ProductionDto productionDto) {
        String token = request.getHeader("token");
        //原材料库存减少
        Integer yclNum = productionDto.getYclNum();
        String yclId = productionDto.getYclId();
        //1.根据id查询原材料剩余数量
        GoodsMaterial goodsMaterial = goodsMaterialMapper.queryById(yclId);
        //2.根据剩余数量 - 需要消耗的原材料   原材料数量
        Integer yclsl = goodsMaterial.getWarehousingNum();
        //判断与源材料数量是否足够
        if(yclsl < yclNum){
            return Result.error(-1, MessageConstant.Material_Num_short);
        }
        //3.求最终剩余数量
        Integer sysl = yclsl - yclNum;
        //当原材料剩余数量为0，则删除该原材料
        if(sysl == 0){
            boolean b = goodsMaterialMapper.deleteById(yclId);
            return b?Result.success():Result.error(-5,MessageConstant.Material_Del_ERROR);
        }
        //4.更新原材料数量
        goodsMaterial.setWarehousingNum(sysl);
        goodsMaterialMapper.updateByNum(goodsMaterial);
        //添加产品数据库
        Production production = BeanUtil.copyProperties(productionDto, Production.class);
        //雪花算法生成产品id
        String cpid = IdUtil.getSnowflake().nextIdStr();
        //解析token拿用户id
        JSONObject jsonObject = JwtUtils.of(token);
        String userId = jsonObject.get("id").toString();
        //获取生产商id
        Integer businessId = goodsMaterial.getBusinessId();
        //根据原材料重量 / 产品净含量 = num；
        Integer num = (int) (goodsMaterial.getWarehousingNum() / productionDto.getNetContent());
        //添加
        production.setId(cpid);
        production.setUserId(userId);
        production.setBusinessId(businessId);
        production.setNum(num);
        productionMapper.addGoods(production);
        return Result.success();
    }

    @Override
    public List<ProductionDto> selectId(Integer id) {
        return productionMapper.selectId(id);
    }


}




